package com.example.partner.activity.home;

import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.partner.R;
import com.example.partner.adapter.user.UserVoAdapter;
import com.example.partner.common.BaseResponse;
import com.example.partner.model.domain.User;
import com.example.partner.model.vo.UserVo;
import com.example.partner.service.UserService;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class NearUsersActivity extends AppCompatActivity {
    private UserService userService;
    //经纬度
    double latitude,longitude;
    ListView listView;
    UserVoAdapter adapter;
    @SuppressLint({"MissingInflatedId", "NonConstantResourceId"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_near_user);
        listView = findViewById(R.id.userList);



        // 初始化Retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL) // 替换为您的服务器地址
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Intent intent = getIntent();
        //获取纬度
        latitude = intent.getDoubleExtra("latitude",0.0);
        //获取经度
        longitude = intent.getDoubleExtra("longitude",0.0);
        userService = retrofit.create(UserService.class);
        getNearUsers(latitude, longitude);
        SharedPreferences sharedPreferences = getSharedPreferences("CurrentUser", Context.MODE_PRIVATE);
        User user = new User();
        user.setId(sharedPreferences.getLong("userId", -1));
        user.setX(longitude);
        user.setY(latitude);
        updateUser(user);


        listView.setOnItemClickListener((adapterView, view, position, l) -> {
            // 获取点击的项
            UserVo selectedUser = (UserVo) adapter.getItem(position);
            String username = selectedUser.getUsername();
            String userTags = selectedUser.getTags();
            String userProfile = selectedUser.getProfile();
            String userRole = String.valueOf(selectedUser.getUserRole());
            String avatarUrl = selectedUser.getAvatarUrl();
            // 创建Intent并启动新的Activity
            Intent newIntent = new Intent(NearUsersActivity.this, UserInfoActivity.class);
            newIntent.putExtra("username", username);
            newIntent.putExtra("userTags", userTags);
            newIntent.putExtra("userProfile", userProfile);
            newIntent.putExtra("userRole", userRole);
            intent.putExtra("avatarUrl",avatarUrl);
            startActivity(intent);
        });


    }

    private void getNearUsers(double latitude, double longitude) {
        userService.searchUserByDistance(5L, 1L, longitude, latitude).enqueue(new Callback<BaseResponse<List<UserVo>>>() {
            @Override
            public void onResponse(Call<BaseResponse<List<UserVo>>> call, Response<BaseResponse<List<UserVo>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    // 从响应中获取用户列表
                    List<UserVo> userVos = response.body().getData();

                    // 在主线程上更新UI
                    runOnUiThread(() -> {
                        if (userVos == null || userVos.isEmpty()) {
                            Toast.makeText(NearUsersActivity.this, "无附近用户", Toast.LENGTH_SHORT).show();
                        } else {
                            adapter = new UserVoAdapter(NearUsersActivity.this, userVos);
                            listView.setAdapter(adapter);
                        }
                    });
                } else {
                    runOnUiThread(() -> Toast.makeText(NearUsersActivity.this, "请求错误", Toast.LENGTH_SHORT).show());
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<List<UserVo>>> call, Throwable t) {
                runOnUiThread(() -> {
                    Toast.makeText(NearUsersActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                    t.printStackTrace();
                });
            }
        });
    }



    private void updateUser(User user) {
        userService.updateUser(user).enqueue(new Callback<BaseResponse<Integer>>() {
            @Override
            public void onResponse(Call<BaseResponse<Integer>> call, Response<BaseResponse<Integer>> response) {
                BaseResponse<Integer> responseBody = response.body();
                Integer count = responseBody.data;
                if (responseBody != null){
                    if (response.isSuccessful()) {
                        if (count == 1){
                            Toast.makeText(NearUsersActivity.this, "位置更新成功", Toast.LENGTH_SHORT).show();
                        }

                        // 基于responseBody进行进一步处理
                    } else {
                        // 处理错误情况
                    }
                }

            }



            @Override
            public void onFailure(Call<BaseResponse<Integer>> call, Throwable t) {
                // 网络错误处理
            }
        });
    }




}
